package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.websocket.DataSyncWebSocketHandler;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 健康检查控制器
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class HealthController {
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ApiResponse<Map<String, Object>> health() {
        Map<String, Object> healthInfo = Map.of(
            "status", "UP",
            "service", "Data Sync API",
            "timestamp", System.currentTimeMillis(),
            "onlineConnections", DataSyncWebSocketHandler.getOnlineCount(),
            "version", "1.0.0"
        );
        return ApiResponse.success(healthInfo);
    }
    
    /**
     * 连接状态检查
     */
    @GetMapping("/connection-status")
    public ApiResponse<Map<String, Object>> connectionStatus() {
        Map<String, Object> status = Map.of(
            "totalConnections", DataSyncWebSocketHandler.getOnlineCount(),
            "customerConnections", DataSyncWebSocketHandler.getOnlineCountByRole("CUSTOMER"),
            "merchantConnections", DataSyncWebSocketHandler.getOnlineCountByRole("MERCHANT"),
            "adminConnections", DataSyncWebSocketHandler.getOnlineCountByRole("ADMIN"),
            "timestamp", System.currentTimeMillis()
        );
        return ApiResponse.success(status);
    }
    
    /**
     * 模拟WebSocket连接
     */
    @PostMapping("/simulate-connection")
    public ApiResponse<String> simulateConnection(
            @RequestParam String userId,
            @RequestParam String role) {
        try {
            // 模拟建立连接
            DataSyncWebSocketHandler handler = new DataSyncWebSocketHandler();
            handler.onConnectionEstablished(userId, role);
            
            return ApiResponse.success("模拟连接建立成功: " + role + "_" + userId);
        } catch (Exception e) {
            return ApiResponse.error("建立连接失败: " + e.getMessage());
        }
    }
    
    /**
     * 模拟断开连接
     */
    @PostMapping("/simulate-disconnect")
    public ApiResponse<String> simulateDisconnect(
            @RequestParam String userId,
            @RequestParam String role) {
        try {
            // 模拟断开连接
            DataSyncWebSocketHandler handler = new DataSyncWebSocketHandler();
            handler.onConnectionClosed(userId, role);
            
            return ApiResponse.success("模拟连接断开成功: " + role + "_" + userId);
        } catch (Exception e) {
            return ApiResponse.error("断开连接失败: " + e.getMessage());
        }
    }
} 